package com.dmzapp.api.servlet;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import com.dmzapp.api.cache.local.LocalCache;
import com.dmzapp.api.cache.redis.MiddleRedisServer;
import com.dmzapp.api.cache.redis.RedisClient;
import com.dmzapp.api.db.AppDao;
import com.dmzapp.api.service.RedisAndDBService;
import com.dmzapp.api.vo.AppInfo;
import com.dmzapp.api.vo.IncomeRecord;
import com.dmzapp.api.vo.LongUseRecord;
import com.dmzapp.api.vo.UserAccount;

/**
 * 
 * 添加有效的特定app长时间使用记录 Servlet implementation class for Servlet:
 * AddEffectiveLongTimeUserRequestHanlder
 * 
 */
public class AddLongTimeUserRequestHanlder extends DMZSerlvet implements
        javax.servlet.Servlet {
    static final long serialVersionUID = 1L;
    private ObjectMapper mapper = new ObjectMapper();

    /**
     * 1. 验证身份，看username对应的deviceid是否匹配 
     * 2. 验证是否已经在服务器有过该用户对此app的使用记录 
     * 3. 验证当前app是否还有余额 
     * 4. 都验证无误后，插入新的income记录
     */
    protected void handle(HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        String deviceid = request.getParameter("d");
//        String macAddress = request.getParameter("m");
        String ip = (String) request.getAttribute("i");
        String username = (String) request.getAttribute("u");
        String packagename = request.getParameter("p");
        
        UserAccount useraccount = RedisClient.getInstance().checkUserExist(username);
        if (useraccount == null) {
            useraccount = AppDao.getInstance().getUserInfo(username);
            if (useraccount != null) {
                RedisClient.getInstance().setUseraccount(useraccount);
            }
        }

        boolean flg = false;
        if (useraccount != null && deviceid.equals(useraccount.getDeviceid())) {
            
            AppInfo tmpApp = LocalCache.getInstance().appCache.get(packagename);
            String useTimesStr = RedisClient.getInstance().checkLongtimeuseEffective(username, packagename);
            int maxTimes = tmpApp.getMax_times();
            
            //TODO: 隐患!要不要在redis中存放全局实时的bid数据，在广告主修改bid后及时生效
            String enduserIncome = String.valueOf(tmpApp.getLongtimeuserFee());
            
            // 如果redis中没有相关数据
            boolean effectiveRecord = false;
            int useTimes = 0;
            if (useTimesStr == null) {
                List<LongUseRecord> longuseRecords = AppDao.getInstance().getLongtimeuseListbyUsernameGroupbypackage(username,
                        tmpApp.getService_id());
                if (longuseRecords != null) {
                    RedisClient.getInstance().setLongtimeusedPackages(username, longuseRecords);
                   
                    boolean packageExist = false;

                    for (LongUseRecord item : longuseRecords) {
                        // 有效条件：packagename 
                        if (item.getPackagename().equals(packagename)){
                            packageExist = true;
                            if(item.getUseTimes() < tmpApp.getMax_times() && MiddleRedisServer.getInstance().checkAndChangeAppRestMoney(packagename, enduserIncome)) {
                                useTimes = item.getUseTimes();
                                effectiveRecord = true;
                            }
                        }
                    }
                    
                    if (!packageExist && tmpApp.getMax_times() > 0 && MiddleRedisServer.getInstance().checkAndChangeAppRestMoney(packagename, enduserIncome)) {
                        effectiveRecord = true;
                    }

                }
            } else {
                useTimes = Integer.valueOf(useTimesStr);
                if (MiddleRedisServer.getInstance().checkAndChangeAppRestMoney(packagename, enduserIncome) && useTimes < maxTimes) {
                    effectiveRecord = true;
                }
            }
            
            
            if (effectiveRecord) {
                // 综合以上为有效安装，操作数据库插入操作,并写入redis中
                IncomeRecord incomeRecord = new IncomeRecord();
                incomeRecord.setDeviceid(deviceid);
                incomeRecord.setIncome(enduserIncome);
                incomeRecord.setIp(ip);
                incomeRecord.setPackagename(packagename);
                incomeRecord.setServiceid(2);
                incomeRecord.setUsername(username);
                incomeRecord.setCreate_time(new Date());
                // 计算该用户的余额
                RedisAndDBService.addUserRestAndAmount(username, enduserIncome);
                
                // 记录用户的收入信息
                RedisAndDBService.inserIncomeDetail(incomeRecord);
                
                // 添加某个用户使用app的次数
                RedisClient.getInstance().addLongtimeUseforuser(username, packagename, useTimes + 1);
                
                flg = true;
            }
        }
        
        Map<String, Object> responseMap = new HashMap<String, Object>();
        responseMap.put("amount", RedisAndDBService.getUserAmount(username));
        responseMap.put("rest", RedisAndDBService.getUserRest(username));
        responseMap.put("server_time", Calendar.getInstance().getTimeInMillis());
        if (flg) {
            responseMap.put("status", "200");
            responseMap.put("msg", "恭喜您，获得体验奖励");
        } else {
            responseMap.put("status", "500");
            responseMap.put("msg", "审核失败");
        }
        try {
            mapper.writeValue(response.getWriter(), responseMap);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}